package com.spc.demo.monitor;

import com.spc.demo.listener.FileListener;
import com.spc.demo.service.ListenerService;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * @author pingchao.su
 * @date 2022/9/5 20:00
 */
@Component
public class FileMonitor implements CommandLineRunner {

    // 监听路径
    private static final String monitorDir = "/tmp/monitor";

    // 设置轮询间隔
    private final long interval = TimeUnit.SECONDS.toMillis(10);

    @Resource
    private ListenerService listenerService;

    /*
     * CommandLineRunner是在所有Bean生成之后，执行一些动作，类似开机自启动
     * */
    @Override
    public void run(String... args) {
        FileAlterationMonitor monitor = createMonitor();
        try {
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public FileAlterationMonitor createMonitor() {
        //带过滤器
        IOFileFilter filter = createIoFileFilter();
        FileAlterationObserver observer = new FileAlterationObserver(new File(monitorDir), filter);

//        //无过滤器
//        FileAlterationObserver observer = new FileAlterationObserver(new File(monitorDir));

        // 向监听者添加监听器，并注入业务服务
        observer.addListener(new FileListener(listenerService));
        // 返回监听者
        return new FileAlterationMonitor(interval, observer);
    }


    // 生成过滤器(函数功能单一原则)
    public IOFileFilter createIoFileFilter() {
        IOFileFilter directories = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), HiddenFileFilter.VISIBLE);
        IOFileFilter files = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".log"));
        return FileFilterUtils.or(directories, files);
    }

}
